<?php

namespace app\admin\controller\kupay;

use app\common\controller\Backend;
use think\Db;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Session;
use app\common\library\kupay\Sms;
use \think\Exception;

/**
 * 工资条记录
 *
 * @icon fa fa-circle-o
 */
class Paylog extends Backend
{

    /**
     * Paylog模型对象
     * @var \app\admin\model\kupay\Paylog
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kupay\Paylog;
        $paytype = Db::name('kupay_paytype')->select();
        $this->assign('paytype', $paytype);
        $company = Db::name('kupay_compay')->find();
        if (empty($company) || empty($company['company'])) {
            $this->assignconfig('companyinfo', 1);
        } else{
            $this->assignconfig('companyinfo', 2);
        }
        $this->assign('company', $company);

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */

//    首页

    public function shows()
    {
        $times = $this->monthlater();
        $times = array_reverse($times);

        $datas = [];
        foreach ($times as $k => $v) {
            $datas[] = Db::name('kupay_paylog')
                ->alias('a')
                ->join('kupay_setlog w', 'a.pid = w.id')
                ->where('status', 1)
                ->where('a.type', 1)
                ->where('times', $v)
                ->count();
        }
        $this->assignconfig('times', $times);

//        微信总条数
        $weixn1 = Db::name('kupay_paylog')->where('type', 1)->count();
        //微信成功
        $weixn2 = Db::name('kupay_paylog')->where('type', 1)->where('status', 1)->count();
//        微信失败
        $weixn3 = Db::name('kupay_paylog')->where('type', 1)->where('status', 0)->count();
        $this->assign('weixn1', $weixn1);
        $this->assign('weixn2', $weixn2);
        $this->assign('weixn3', $weixn3);

//        短信
        $duanxin1 = Db::name('kupay_paylog')->where('type', 4)->count();
        $duanxin2 = Db::name('kupay_paylog')->where('type', 4)->where('status', 1)->count();
        $duanxin3 = Db::name('kupay_paylog')->where('type', 4)->where('status', 0)->count();
        $this->assign('duanxin1', $duanxin1);
        $this->assign('duanxin2', $duanxin2);
        $this->assign('duanxin3', $duanxin3);
        $this->assignconfig('datas', $datas);
        $weixinconfig = Db::name('kupay_config')->where('name', 'weixin')->find();
        $weixinconfig = empty($weixinconfig['value'])?'':unserialize($weixinconfig['value']);
        $this->assign('weixinconfig', $weixinconfig);


        return $this->view->fetch();
    }

    public function showtypman($type)
    {
        $times = $this->monthlater();
        $times = array_reverse($times);
        $this->assignconfig('times', $times);
        $datas = [];
        foreach ($times as $k => $v) {
            $datas[] = Db::name('kupay_paylog')
                ->alias('a')
                ->join('kupay_setlog w', 'a.pid = w.id')
                ->where('status', 1)
                ->where('a.type', $type)
                ->where('times', $v)
                ->count();
        }
        $this->success($datas);
    }

    public function showtypprice($type)
    {
        $times = $this->monthlater();
        $times = array_reverse($times);
        $this->assignconfig('times', $times);
        $datas = [];
        foreach ($times as $k => $v) {
            $datas[] = Db::name('kupay_paylog')
                ->alias('a')
                ->join('kupay_setlog w', 'a.pid = w.id')
                ->where('status', 1)
                ->where('a.type', $type)
                ->where('times', $v)
                ->sum('price');

        }
        $this->success($datas);
    }

    protected function monthlater()
    {
        $str = array();
        for ($i = 1; $i < 13; $i++) {
            $str[$i - 1] = date('Y-m', strtotime('-' . $i . 'month'));//包含本月
            //$str[$i] =date('Y-m',strtotime('-1month-'.$i.'month'));//不包含本月
        }
        return $str;
    }


//    基础配置
    public function config()
    {
        $weixn = Db::name('kupay_config')->where('name', 'weixin')->find();
        $weixn = empty($weixn['value'])?'':unserialize($weixn['value']);
        if (!isset($weixn['types'])) {
            if(empty($weixn)){
                $weixn=[];
            }
            $weixn['types'] = 1;
        }
        $shortmessage = Db::name('kupay_config')->where('name', 'shortmessage')->find();
        $shortmessage = empty($shortmessage['value'])?'':unserialize($shortmessage['value']);
        $this->assign('weixn', $weixn);
        $this->assign('shortmessage', $shortmessage);
        return $this->view->fetch();
    }

    //    基础配置
    public function configsave()
    {
        $input = input();
        $input = input();
        $name = $input['name'];
        unset($input['name']);

        $list = Db::name('kupay_config')->where('name', $name)->find();
        if (!empty($list)) {
            $data = ['value' => serialize($input)];
            if (Db::name('kupay_config')->where('name', $name)->update($data)) {
                $this->success('修改成功！');
            } else {
                $this->error('修改失败！');
            }
        } else {
            $data = ['value' => serialize($input),
                'name' => $name];
            if (Db::name('kupay_config')->insert($data)) {
                $this->success('修改成功！');
            } else {
                $this->error('修改失败！');
            }
        }
    }


//    新增工资条
    public function index()
    {
        $info = Session::get('kupay_table');
        $info = empty($info)?'':$info[0];
        $tags = Session::get('kupay_tags');
        $this->assign('info', $info);
        $this->assign('tags', $tags);
        $weixin = Db::name('kupay_config')->where('name', 'weixin')->find();
        $weixin = empty($weixin['value'])?'':unserialize($weixin['value']);
        $this->assign('weixin', $weixin);
        return $this->view->fetch();
    }

//    查询上传数据
    public function infos()
    {
        $info = Session::get('kupay_table');
        $info = empty($info)?'':$info[0];
        $tags = Session::get('kupay_tags');
        $this->success($info, '', $tags);
    }

//    存记录
    public function sendsave()
    {
        $company = Db::name('kupay_compay')->find();
        $input = input();
        $info = Session::get('kupay_table');
        $infos = $info;
        $selected = isset($input['selected'])?$input['selected']:'';
        if(!empty($selected)){
            foreach ($selected as $ks => $vs) {
                if($vs==$input['name']){
                    $this->error('发送失败！，请不要隐藏'.$input['name']);
                } else if($vs==$input['phone']){
                    $this->error('发送失败！，请不要隐藏'.$input['phone']);
                }else if($vs==$input['email']){
                    $this->error('发送失败！，请不要隐藏'.$input['email']);
                }else if($vs==$input['price']){
                    $this->error('发送失败！，请不要隐藏'.$input['price']);
                }
            }
        }
        if ($input['kongzhi'] == 1) {
            foreach ($info as $k => $v) {
                foreach ($v as $ks => $vs) {
                    if (!empty($selected)) {
                        if (in_array($ks, $selected)) {
                            unset($info[$k][$ks]);
                        }
                    }


                }
            }

        } else {
            foreach ($info as $k => $v) {
                foreach ($v as $ks => $vs) {
                    if (empty($vs)) {
                        unset($info[$k][$ks]);

                    } else {
                        if (!empty($selected)) {
                            if (in_array($ks, $selected)) {
                                unset($info[$k][$ks]);
                            }
                        }
                    }

                }
            }
        }
        $tags = Session::get('kupay_tags');
        $sends = explode(',', $input['sends']);
        $setid = 0;
        $num = 0;
        $stat = 1;
        // 启动事务
        Db::startTrans();
        try {

            foreach ($tags as $tag_k => $tag_v) {
                $ttype = Db::name('kupay_paylog_rule')->where('name', $tag_v)->find();
                if (empty($ttype)) {
                    $data_tag = ['name' => $tag_v];
                    Db::name('kupay_paylog_rule')->insert($data_tag);
                }
            }
            $data_log = [
                'type' => $input['type'],
                'times' => $input['time'],
                'timing' => strtotime($input['dingshi']),
                'createtime' => time(),
                'static' => empty($input['dingshi'])?3:1,

            ];
            $pid = Db::name('kupay_setlog')->insertGetId($data_log);
            $setid = $pid;
            foreach ($sends as $sends_k => $sends_v) {
                foreach ($info as $da_k => $da_v) {
                    $data_pay = [
                        'notice' => $input['gongao'],
                        'pid' => $pid,
                        'status' => 0,
                        'name' => $da_v[$input['name']],
                        'phone' => $da_v[$input['phone']],
                        'email' => isset($da_v[$input['email']]) ? $da_v[$input['email']] : '',
                        'price' => $infos[$da_k][$input['price']],
                        'type' => $sends_v,
                        'createtime' => time(),
                        'updatetime' => time(),
                        'company' => $company['company'] ? $company['company'] : '',
                    ];
                    $lid = Db::name('kupay_paylog')->insertGetId($data_pay);
                    $num = $num + 1;
                    foreach ($da_v as $da1_k => $da1_v) {
                        $rid = Db::name('kupay_paylog_rule')->where('name', $da1_k)->find();
                        $data2 = [
                            'paylog_id' => $lid,
                            'paylog_rule_id' => $rid['id'],
                            'content' => $da1_v,
                        ];

                        Db::name('kupay_paylog_auth')->insert($data2);
                    }

                }
            }
            $stat = 2;
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        $nu = ['num' => $num, 'dingshi' => empty($input['dingshi']) ? '1' : $input['dingshi']];
        if ($stat == 2) {
            $this->success($setid, '', $nu);
        } else {
            $this->error('发送失败！');
        }
    }


    //    总发送
    public function sends()
    {
        $input = input();
        $company = Db::name('kupay_compay')->find();
        $paylog = Db::name('kupay_paylog')->where('pid', $input['id'])->page($input['page'],$input['limit'])->select();
        $setlog = Db::name('kupay_setlog')->where('id', $input['id'])->find();
        sleep(1);
        $oks = 0;
        $errs = 0;
        foreach ($paylog as $k => $v) {
            $static = 0;
            if ($v['type'] == 1) {
                $static = $this->weixin($v['id']);
            } else if ($v['type'] == 4) {
                $msgs = '{"name":"' . $v['name'] . '-' . $v['company'] . '","time":"' . $setlog['times'] . '","content":"' . $setlog['type'] . '","code":"index/kupay/index"}';
                $static = $this->duanxin($v['phone'], $msgs);
            }

            if ($static == 0) {
                $errs = $errs + 1;
            } else {
                $oks = $oks + 1;
                $data = [
                    'updatetime' => time(),
                    'status' => $static,
                ];
                Db::name('kupay_paylog')->where('id', $v['id'])->update($data);
            }
        }
        $this->success($oks, '', $errs);
    }

//    单发送
    public function sendsone($id, $type)
    {
        $company = Db::name('kupay_compay')->find();
        $paylog = Db::name('kupay_paylog')->where('id', $id)->find();
        $setlog = Db::name('kupay_setlog')->where('id', $paylog['pid'])->find();
        $static = 0;
        if ($type == 1) {
            $static = $this->weixin($paylog['id']);

        }  else if ($type == 4) {
            $msgs = '{"name":"' . $paylog['name'] . '-' . $paylog['company'] . '","time":"' . $setlog['times'] . '","content":"' . $setlog['type'] . '","code":"index/kupay/index"}';
            $static = $this->duanxin($paylog['phone'], $msgs);
        }
        $data = [
            'updatetime' => time(),
            'status' => $static,
        ];
        if (Db::name('kupay_paylog')->where('id', $id)->update($data)) {

            if($static==1){
                $this->success('发送成功！');
            } else{
                $this->success('发送失败！');
            }
        } else {
            $this->error('发送失败！');
        }
    }

    //    单发送
    public function sendsones($id, $type)
    {
        $company = Db::name('kupay_compay')->find();
        $paylog = Db::name('kupay_paylog')->where('id', $id)->find();
        $setlog = Db::name('kupay_setlog')->where('id', $paylog['pid'])->find();
        $static = 0;
        if ($type == 1) {
            $static = $this->weixin($paylog['id']);

        }  else if ($type == 4) {
            $msgs = '{"name":"' . $paylog['name'] . '-' . $paylog['company'] . '","time":"' . $setlog['times'] . '","content":"' . $setlog['type'] . '","code":"index/kupay/index"}';
            $static = $this->duanxin($paylog['phone'], $msgs);
        }
        $data = [
            'updatetime' => time(),
            'status' => $static,
        ];
        Db::name('kupay_paylog')->where('id', $id)->update($data);
    }

    public function sendsoneall($id,$page,$limit,$type){
        $list = Db::name('kupay_paylog')
            ->where('pid', $id)
            ->where('type', $type)
            ->page($page,$limit)
            ->select();
        foreach ($list as $k => $v) {
            $this->sendsones($v['id'], $type);
        }
        $this->success('发送成功！');

    }
    public function sendsoneallerr($id,$page,$limit,$type)
    {

        $list = Db::name('kupay_paylog')
            ->where('pid', $id)
            ->where('type', $type)
            ->where('status', 0)
            ->page($page,$limit)
            ->select();

        foreach ($list as $k => $v) {
            $this->sendsones($v['id'], $type);
        }
        $this->success('发送成功！');
    }





    protected function duanxin($tel, $vcode)
    {
        $sms = new Sms();

//测试模式
        $results = $sms->send_verify($tel, $vcode);
        if ($results) {
            return 1;
        } else {
            return 0;
        }
    }



//    微信发送
    protected function weixin($id)
    {
        $weixin = Db::name('kupay_config')->where('name', 'weixin')->find();
        $weixin = unserialize($weixin['value']);
        $paylog = Db::name('kupay_paylog')->where('id', $id)->find();
        $setlog = Db::name('kupay_setlog')->where('id', $paylog['pid'])->find();
        $user = Db::name('kupay_user')->where('phone', $paylog['phone'])->find();
        if (empty($user) || empty($user['openid'])) {
            return 0;
        }
        $times = date('Y-m-d H:i:s', time());
        $appid = $weixin['appid'];
        $secret = $weixin['appsecret'];
        $appinfo = $weixin['appinfo'];
        $types = isset($weixin['types']) ? $weixin['types'] : 1;//控制新版，还是旧版
        $time = date('Y-m-d H:i:s', time());
        $urls = request()->domain().'/index/kupay/index';
        if ($types == 1) {
            $template = [
                'touser' => $user['openid'],
                'template_id' => $appinfo, // 填写你自己的消息模板ID
                'url' => $urls,
                'data' => [ // 模板消息内容，根据模板详情进行设置
                    'keyword1' => ['value' => urlencode($paylog['name'])],
                    'keyword2' => ['value' => urlencode($setlog['times'])],
                    'keyword3' => ['value' => urlencode($times)],
                ],
            ];
        } else {
            $template = [
                'touser' => $user['openid'],
                'template_id' => $appinfo, // 填写你自己的消息模板ID
                'url' => $urls,
                'data' => [ // 模板消息内容，根据模板详情进行设置
                    'thing8' => ['value' => urlencode($paylog['company'])],
                    'time3' => ['value' => urlencode($setlog['times'])],
                    'time5' => ['value' => urlencode($times)],
                ],
            ];
        }

        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;

        $access_token = '';
        if (Session::has('access_tokens')) {
            if (empty(Session::get('access_tokens'))) {
                $access_token = json_decode(self::curl_post($url), true);
                $access_token = $access_token['access_token'];
                Session::set('access_token_times', time() + 100);
                Session::set('access_tokens', $access_token);
            } else {
                if (Session::get('access_token_times') < time()) {
                    $access_token = Session::get('access_tokens');
                } else {
                    $access_token = json_decode(self::curl_post($url), true);
                    $access_token = $access_token['access_token'];
                    Session::set('access_token_times', time() + 100);
                    Session::set('access_tokens', $access_token);
                }
            }

        } else {
            $access_token = json_decode(self::curl_post($url), true);
            $access_token = $access_token['access_token'];
            Session::set('access_token_times', time() + 100);
            Session::set('access_tokens', $access_token);
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $dataRes=[];
        try{
            $dataRes = $this->curl_post($url, urldecode($json_template));
            $dataRes = json_decode($dataRes, true);
        }catch(\Exception $e){
            $this->error('配置错误');
        }
        if ($dataRes['errcode'] == 0) {
            return 1;
        } else {
            return 0;
        }


    }


    protected function curl_post($url, $data = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

//    发薪类型查询
    public function type()
    {
        return $this->view->fetch();
    }

//发薪类型新增
    public function typesave()
    {
        $input = input();
//        $input = $input['row'];
        $data = ['name' => $input['name']];
        $info = Db::name('kupay_paytype')->where('name', $input['name'])->find();
        if (!empty($info)) {
            $this->error('类型已存在！');
        }

        if (Db::name('kupay_paytype')->insert($data)) {
            $infos = Db::name('kupay_paytype')->select();
            $this->success('添加成功！', '', $infos);
        } else {
            $this->error('添加失败！');
        }

    }

//发薪类型编辑
    public function paytypeedit($ids)
    {
        $info = Db::name('kupay_paytype')->where('id', $ids)->find();
        $this->assign('info', $info);
        return $this->view->fetch();

    }

//发薪类型更新
    public function typeupdate()
    {
        $input = input();
        $data = ['name' => $input['name']];
        $info = Db::name('kupay_paytype')->where('id', '<>', $input['id'])->where('name', $input['name'])->find();
        if (!empty($info)) {
            $this->error('类型已存在！');
        }
        if (Db::name('kupay_paytype')->where('id', $input['id'])->update($data)) {
            $infos = Db::name('kupay_paytype')->select();
            $this->success('编辑成功！', '', $infos);
        } else {
            $this->error('编辑失败！');
        }

    }

//发薪类型删除
    public function typedel($ids)
    {
        if (Db::name('kupay_paytype')->where('id', $ids)->delete($ids)) {
            $infos = Db::name('kupay_paytype')->select();
            $this->success('删除成功！', '', $infos);
        } else {
            $this->error('删除失败！');
        }

    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }
        $tags = [];
        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getFormattedValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                $k = 1;
                foreach ($temp as $k => $v) {
                    if ($k !== '') {
                        $tags[] = $k;
                        $row[$k] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        if (!empty($insert)) {
            $tags = array_flip(array_flip($tags));
            $tags = implode(',', $tags);
            $tags = explode(',', $tags);
        }
        $info = [];
        foreach ($insert as $k => $v) {
            $infos = implode('', $v);
            if (!empty($infos)) {
                $info[] = $v;
            }
        }
        Session::set('kupay_table', $info);
        Session::set('kupay_tags', $tags);
        $data=[];
        $data['info']=$info;
        $data['tags']=$tags;
        $this->success('上传成功', '', $data);
    }

}
